<script setup>
import { onMounted, onUnmounted, ref, h } from "vue";
import { RollbackOutlined } from '@ant-design/icons-vue';
import AMapLoader from "@amap/amap-jsapi-loader";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";

const router = useRouter()
let map = null;
let driving = null;
let transfer = null;
let walking = null;
let markers = [];
const data = JSON.parse(localStorage.getItem('Driver'))
const type = localStorage.getItem('Type')
let driverPoints = ref([])
for (let i = 0; i < data.length; i++) {
    driverPoints.value.push({
        id: data[i].key,
        name: data[i].name,
        address: data[i].address,
        location: data[i].location.split(',')
    })
}


onMounted(() => {
    window._AMapSecurityConfig = {
        securityJsCode: "d4b6fd7e43806c92464ef69f7cc938d5",
    };
    AMapLoader.load({
        key: "525d19eaad172b7619b29b5138a297db", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        // plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
    }).then((AMap) => {
        map = new AMap.Map("Drivercontainer", {
            // 设置地图容器id
            // viewMode: "3D", // 是否为3D地图模式
            zoom: 11, // 初始化地图级别
            center: [116.397428, 39.90923], // 初始化地图中心点位置
        });

        const startPoint = new AMap.LngLat(Number(driverPoints.value[0].location[0]), Number(driverPoints.value[0].location[1]));
        const endPoint = new AMap.LngLat(Number(driverPoints.value[data.length - 1].location[0]), Number(driverPoints.value[data.length - 1].location[1]));
        let middlePoint = []
        console.log(typeof startPoint.lng);

        if (data.length > 2) {
            for (let i = 1; i < driverPoints.value.length - 1; i++) {
                middlePoint.push(new AMap.LngLat(Number(driverPoints.value[i].location[0]), Number(driverPoints.value[i].location[1])))
            }
        }
        if (type == 'Car') {
            console.log('succcss');
            car(startPoint, endPoint, middlePoint)
        } else if (type == 'Public') {
            publicguide(startPoint, endPoint, middlePoint)
        } else if (type == 'Walk') {
            Walk([startPoint.lng, startPoint.lat], [endPoint.lng, endPoint.lat])
        }
        addmarker()
    })
        .catch((e) => {
            console.log(e);
        });
});
//驾车路线规划
const car = (startPoint, endPoint, middlePoint) => {
    new AMap.plugin(["AMap.Driving"], function () { //加载驾车服务插件
        let drivingOptions = {
            //驾车策略，包括 LEAST_TIME，LEAST_FEE, LEAST_DISTANCE,REAL_TRAFFIC
            policy: AMap.DrivingPolicy.LEAST_TIME, // 其它policy参数请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingPolicy
            // ferry: 1, // 是否可以使用轮渡
            // province: '京', // 车牌省份的汉字缩写 
            map: map,
            panel: 'panel',
            autoFitView: true,
            hideMarkers: true
        };
        driving = new AMap.Driving(drivingOptions);
        // 根据起终点经纬度规划驾车导航路线
        driving.search(startPoint, endPoint, {
            waypoints: middlePoint
        }, function (status, result) {
            // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
            if (status === 'complete') {
                message.success('驾车路线规划完成')
            } else {
                message.error('获取驾车数据失败')
                console.log(result);
            }
        });
    });
}
//公共交通路线规划
const publicguide = (startPoint, endPoint, middlePoint) => {
    const city = JSON.parse(localStorage.getItem('cityData'))
    new AMap.plugin(["AMap.Transfer"], function () { //加载公交换乘插件
        let transOptions = {
            map: map,
            panel: 'panel',
            city: city,
            policy: AMap.TransferPolicy.LEAST_TIME,
            hideMarkers: true
        };
        //构造公交换乘类
        transfer = new AMap.Transfer(transOptions);
        //根据起、终点坐标查询公交换乘路线
        transfer.search(startPoint, endPoint, function (status, result) {
            // result即是对应的公交路线数据信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_TransferResult
            if (status === 'complete') {
                message.success('公交路线规划完成')
            } else {
                message.error('公交路线数据查询失败')
                console.log(result);

            }
        });
    });
}
//步行路线规划
const Walk = (startPoint, endPoint) => {
    new AMap.plugin(["AMap.Walking"], function () { //加载步行导航插件
        walking = new AMap.Walking({
            map: map,
            panel: "panel",
            hideMarkers: true
        });  //构造步行导航类
        //根据起终点坐标规划步行路线
        walking.search(startPoint, endPoint, function (status, result) {
            // result即是对应的步行路线数据信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_WalkingResult
            if (status === 'complete') {
                message.success('步行路线规划完成')
            } else {
                message.error('步行路线数据查询失败')
                console.log(result);
            }
        });
    });
}
//添加标记点
const addmarker = () => {
    markers = []
    // 创建一个 Icon
    let startIcon = new AMap.Icon({
        size: new AMap.Size(30, 40),
        image: 'http://localhost:3000/uploads\\1742193924897-start.jpg',
        imageSize: new AMap.Size(45, 45),
        imageOffset: new AMap.Pixel(-8, -2)
    });
    let endIcon = new AMap.Icon({
        size: new AMap.Size(30, 40),
        image: 'http://localhost:3000/uploads\\1742193928632-end.jpg',
        imageSize: new AMap.Size(45, 45),
        imageOffset: new AMap.Pixel(-8, -2)
    });
    for (let i = 0; i < data.length; i++) {
        if (i === 0) {
            markers[i] = new AMap.Marker({
                position: driverPoints.value[i].location,
                title: '起点' + data[i].name,
                icon: startIcon
            });

        } else if (i === data.length - 1) {
            markers[i] = new AMap.Marker({
                position: driverPoints.value[i].location,
                title: '终点' + data[i].name,
                icon: endIcon
            });
        } else {
            markers[i] = new AMap.Marker({
                position: driverPoints.value[i].location,
                title: data[i].name,
            });
        }

        markers[i].on('click', (e) => {
            let content = `
      <div style="width: 200px; height: 100px; font-size:14px;  "  >
        <h3>${data[i].name}</h3>
        <p>地址：${data[i].address}</p>
      </div>
      `
            let infoWindow = new AMap.InfoWindow({
                // isCustom: true, //使用自定义窗体
                content: content,
                // offset: new AMap.Pixel(10, -10),
                anchor: "bottom-right",
            });
            infoWindow.open(map, e.target.getPosition());
            //根据覆盖物范围调整视野
            map.setFitView([markers[i]])
        })
        map.add(markers[i]);
    }
}
//路由跳转函数
const gotoHome = () => {
    router.push('/')
}
onUnmounted(() => {
    map?.destroy();
});
</script>

<template>
    <div id="Drivercontainer">
    </div>
    <div id="tartitle">
        <div style="color: green; margin: 10px;font-size: 14px;">{{ data[0].name }}->{{ data[data.length - 1].name }}
        </div>
        <a-button danger type="text" @click="gotoHome" :icon="h(RollbackOutlined)">返回首页</a-button>
    </div>
    <div id="panel">
    </div>
</template>

<style scoped>
#Drivercontainer {
    width: 100%;
    height: 100vh;
}

#tartitle {
    position: fixed;
    background-color: white;
    width: 280px;
    height: 75px;
    z-index: 1;
    display: flex;
    justify-content: space-between;
    top: 0;
    right: 10%;
}

#panel {
    position: fixed;
    background-color: white;
    max-height: 90%;
    overflow-y: auto;
    top: 6%;
    right: 10%;
    width: 280px;
}

#panel .amap-lib-driving {
    border-radius: 4px;
    overflow: hidden;
}
</style>
